<?php

namespace App\Jobs;

use App\Constant\ThirdMoneyCode;
use App\Library\Guzzle\MoneyPlatformRequest;
use App\Listeners\CollectionReceiptListener;
use App\Models\CollectionApiRequest;
use App\Models\RepayRecord;
use App\Models\RepaySummary;
use App\Models\Traits\Repay;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class ProcessWriteOff implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, Repay;

    protected $summary;

    protected $record;

    /**
     * 任务可以尝试的最大次数。
     *
     * @var int
     */
    public $tries = 5;

    /**
     * 定义任务超时时间
     *
     * @return \DateTime
     */
    public function retryUntil()
    {
        return now()->addSeconds(5);
    }

    /**
     * 创建一个新的任务实例。
     *
     * @return void
     */
    public function __construct(RepaySummary $summary, RepayRecord $record)
    {
        $this->summary = $summary;
        $this->record = $record;
    }

    /**
     * 运行任务。
     *
     * @return bool
     */
    public function handle()
    {
        $date = date('Y-m-d H:i:s');
        $data['third_repay_id'] = $this->summary->loan_id;
        $data['trade_no'] = '';
        \Log::debug('pay_compensate', ['message' => '测试: '.print_r($data,true)]);
        $obj = new MoneyPlatformRequest();
        $res = $obj->getMoneyRepayResult($data);
        if($res['subCode'] == ThirdMoneyCode::RESULT_STATUS_SUCCESS) {
            $this->_success();
            \Log::debug('pay_compensate', ['message' => '['. $date.'] 销账:loan_id 是' . $this->id .'的订单销账成功。']);
            return true;
        } elseif($res['subCode'] == ThirdMoneyCode::RESULT_STATUS_PROCESSING) {
            $this->_error();
            \Log::debug('pay_compensate', ['message' => '['. $date.'] 销账:loan_id 是' . $this->id .'的订单销账正在进行中。']);
            return false;
        } else {
            $this->_error();
            \Log::debug('pay_compensate', ['message' => '['. $date.'] 销账:loan_id 是' . $this->id .'的订单销账失败。']);
            return false;
        }
    }

    private function _success()
    {
        if(Repay::setCurrentPeriodSuccess($this->record)){
            $this->record->status = RepayRecord::STATUS_FOUR;
            $this->record->save();
        }
        $obj = new CollectionReceiptListener();
        $obj->writeOffEvent($this->record);
    }


    private function _error()
    {
        $obj = new CollectionReceiptListener();
        $obj->writeOffEvent($this->record);
    }
}
